<?php
/**
 * Description
 *
 * PHP version 7
 *
 * @category Custom
 * @package  Custom
 * @author   ryu <mo5467@126.com>
 * @date     2020-04-29 23:47:11
 * @lastTime 2020-05-02 00:08:19
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     none
 */
namespace Design\Other\Repository;

class PostStatus
{
    const STATE_DRAFT_ID     = 1;
    const STATE_PUBLISHED_ID = 2;

    const STATE_DRAFT     = 'draft';
    const STATE_PUBLISHED = 'published';

    private static $validState = [
        self::STATE_DRAFT_ID     => self::STATE_DRAFT,
        self::STATE_PUBLISHED_ID => self::STATE_PUBLISHED,
    ];

    private $id;

    private $name;


    public static function fromInt(int $id) : PostStatus
    {
        self::ensureValidId($id);
        return new self($id, self::$validState[$id]);

    }//end fromInt()


    public static function fromString(string $status) : PostStatus
    {
        self::ensureValidName($status);

        $state = array_search($status, self::$validState);


        return new self(
            $state,
            $status
        );

    }//end fromString()


    private function __construct(int $id, string $status)
    {
        $this->id   = $id;
        $this->name = $status;

    }//end __construct()


    public function toInt() : int
    {
        return $this->id;

    }//end toInt()


    public function toString() : string
    {
        return $this->name;

    }//end toString()


    public static function ensureValidId(int $id)
    {
        if (!in_array($id, array_keys(self::$validState))) {
            throw new \InvalidArgumentException('Invalid id given');
        }

    }//end ensureValidId()


    public static function ensureValidName(string $status)
    {
        if (!in_array($status, self::$validState, true)) {
            throw new \InvalidArgumentException('Invalid id given');
        }

    }//end ensureValidName()


}//end class
